var theLift = function (queues, capacity) {
    var stays = [];
    var isUp = true;
    var people_in_lift = [];
    function need_stay(i) {
        //如果电梯里有人需要下则要停
        if (people_in_lift.indexOf(i) > -1) return true;
        //电梯方向与乘客方向一致需要停
        if (isUp && queues[i].findIndex(v => v > i) > -1) return true;
        if (!isUp && queues[i].findIndex(v => v < i) > -1) return true;
    }

    function take_lift(i) {
        var people_go_up = queues[i].filter(v => v > i);
        var people_go_down = queues[i].filter(v => v < i);
        if (isUp) {
            while (people_in_lift.length < capacity && people_go_up.length) {
                people_in_lift.push(people_go_up.shift());
            }
        } else {
            while (people_in_lift.length < capacity && people_go_down.length) {
                people_in_lift.push(people_go_down.shift());
            }
        }
        queues[i] = people_go_up.concat(people_go_down);
    }

    stays.push(0);
    while (queues.findIndex(v => v.length > 0) > -1) {
        for (var i = 0; i < queues.length; i++) {
            if (need_stay(i)) {
                if (stays[stays.length - 1] !== i) stays.push(i);
                //下电梯
                people_in_lift = people_in_lift.filter(v => v != i);
                take_lift(i);
            }
            //maybe check if no people in front then siwtch to down better
        }
        isUp = false;
        for (var i = queues.length - 1; i > -1; i--) {
            if (need_stay(i)) {
                if (stays[stays.length - 1] !== i) stays.push(i);
                //下电梯
                people_in_lift = people_in_lift.filter(v => v != i);
                take_lift(i);
            }
        }
        isUp = true;
    }
    if (stays[stays.length - 1]) stays.push(0);
    return stays;
}
var queues = [[3, 3, 3, 3, 3, 3], [], [], [], [], [4, 4, 4, 4, 4, 4], []]
console.log(theLift(queues, 5))